﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.BlobStoring;
using Volo.Abp.Domain.Repositories;

namespace WeChat.CMS.Attachments
{
    [RemoteService(false)]
    public class AttachmentAppService : CMSAppService, IAttachmentAppService
    {
        private readonly IBlobContainer<AttachmentContainer> _blobContainer;
        private readonly IAttachmentRepository _attachmentRepository;

        public AttachmentAppService(IBlobContainer<AttachmentContainer> blobContainer, IAttachmentRepository attachmentRepository)
        {
            _blobContainer = blobContainer;
            this._attachmentRepository = attachmentRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileExt"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task<AttachmentDTO> AddAttachment(string fileName, string fileExt, string contentType, byte[] bytes)
        {
            string blobName = $"{DateTime.Now.ToString("yyyyMM")}/{GuidGenerator.Create()}{fileExt}";
            await SaveBlobAsync(blobName, bytes);
            Attachment attachment = new Attachment()
            {
                BlobName = blobName,
                FileName = fileName,
                FileExtension = fileExt,
                ContentType = contentType,

            };
            var result = await _attachmentRepository.InsertAsync(attachment);
            return ObjectMapper.Map<Attachment, AttachmentDTO>(result);
        }

        public async Task<FileResultDTO> GetAttachment(Guid attachmentId)
        {
            FileResultDTO result = new FileResultDTO();
            var attachmentRecord = await _attachmentRepository.FirstAsync(ac => ac.Id.Equals(attachmentId));
            if (attachmentRecord == null)
            {
                result = null;
            }
            else
            {
                var fileBytes = await _blobContainer.GetAllBytesOrNullAsync(attachmentRecord.BlobName);
                if (fileBytes == null)
                {
                    result = null;
                }
                else
                {
                    result.FileBytes = fileBytes;
                    result.ContentType=attachmentRecord.ContentType;
                    result.FileName= attachmentRecord.FileName;
                }
            }
            return result;
        }
        private async Task SaveBlobAsync(string blobName, byte[] bytes)
        {
            //blobName = $"{DateTime.Now.ToString("yyyyMM")}/{GuidGenerator.Create()}";
            await _blobContainer.SaveAsync(blobName, bytes);

        }
    }
}
